import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './index.less';
import AddSelfFetch from './addModal';
import EditSelfFetch from './editModal';
import { Card, Switch, Input, Radio, Checkbox, Form, Button, message, Spin, Row, Col,Popconfirm, Tag,Icon, Table } from 'antd';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const namespace = 'selfFetch'
@Form.create()
class SelfFetch extends Component {
  state = {
    loadBtn:false,
    paginationProps: {
      showSizeChanger: true,
      showQuickJumper: false,
      showTotal: total => `共 ${total} 条记录`,
      pageSize: 10,
      total: 0,
      pageIndex: 1,
    },
    loading:false,
    selfFetchConfig:{},
    switchLoading:false,
    Payment:[],
    editData:{},
    pageLoading:true
  }

  componentWillMount() {
    window.Isoption = false;
  }

  componentDidMount(){
    window.Isoption = true;
    this.getAddressList();
    this.getSelfFetchConfig();
    setTimeout(()=>{
      this.setState({pageLoading:false})
    },1000)
  }
  //获取自提地址列表
  getAddressList = () => {
    const { dispatch } = this.props;
    const { paginationProps } = this.state;
    this.setState({loading:true})
    dispatch({
      type: 'selfFetch/GetPickupAddressPageData',
      payload: {
        page: paginationProps.pageIndex,
        size: paginationProps.pageSize
      },
      callBack: {
        success: res =>{
          console.log(res)
          this.setState({
            paginationProps: { ...this.state.paginationProps, total: res.Data.Total },
            loading:false
          })
        },
        error: res =>{
          this.setState({loading:false})
        }
      }
    });
  }

  //获取上门自提设置
  getSelfFetchConfig = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'selfFetch/GetSelfFetchConfig',
      callBack: {
        success: res =>{
          let cPayment=[];
          if (res.Data.Config.IsSupportCOD) {
            cPayment.push(2)
          }
          if (res.Data.Config.IsSupportOnlinePay) {
            cPayment.push(1)
          }
          this.props.form.setFieldsValue({
            Payment:cPayment
          })
          this.setState({selfFetchConfig:res.Data,switchLoading:false,Payment:cPayment})
        },
        error: res =>{
          message.error(res.Msg)
          this.setState({switchLoading:false})
        }
      }
    });
  }
  //上门自提设置
  handleSubmit = ()=>{
    const { dispatch, form } = this.props;
    form.validateFields((err, values) => {
      if (values.Payment) {
        let param={};
        let IsSupportOnlinePayIndex = values.Payment.findIndex(item => item == 1)
        if (IsSupportOnlinePayIndex > -1) {
          param = {...param, SupportOnlinePay: true }
        } else {
          param = { ...param,SupportOnlinePay: false }
        }
        let IsSupportCODIndex = values.Payment.findIndex(item => item == 2)
        if (IsSupportCODIndex > -1) {
          param = {  ...param,SupportCOD: true }
        } else {
          param = { ...param, SupportCOD: false }
        }
        this.setState({loadBtn:true})
        dispatch({
          type: `${namespace}/SaveSelfFetchSupportPay`,
          payload: param,
          callBack: {
            success: (data) => {
              this.setState({loadBtn:false})
              message.success("保存成功");
            },
            error: (data) => {
              this.setState({loadBtn:false})
              message.error("保存失败：" + data.Msg);
            }
          }

        });
      }
    })
  }

  //打开添加自提点弹窗
  addSelfFetch = ()=>{
    this.SelfFetch.showModal();
  }

  //打开编辑自提点弹窗
  editRow = (record)=>{
    console.log(record)
    this.setState({editData:record},()=>{
      this.editSelfFetch.getRowData();
      this.editSelfFetch.showModal();
    })

  }

  //分页
  handleTableChange = (pagination, filters, sorter)=>{
    this.setState(
      {
        loading: true,
        paginationProps: {
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showTotal: total => `共 ${total} 条记录`,
          pageIndex: pagination.current,
        },

      },()=>{
        this.getAddressList();
      })

  }
  openSelfFetch = () =>{
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/OpenSelfFetchDelivery`,
      callBack: {
        success: (data) => {
          message.success("已开启");
          this.getSelfFetchConfig();
        },
        error: (data) => {
          message.error("开启失败：" + data.Msg);
          this.setState({switchLoading:false})
        }
      }
    });
  }
  closeSelfFetch = () =>{
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/CloseSelfFetchDelivery`,
      callBack: {
        success: (data) => {
          message.success("已关闭");
          this.getSelfFetchConfig();
        },
        error: (data) => {
          message.error("关闭失败：" + data.Msg);
          this.setState({switchLoading:false})
        }
      }
    });
  }
  setSelfFetchConfig = (checked) =>{
    this.setState({switchLoading:true})
    if(checked){
      this.openSelfFetch();
    }else{
      this.closeSelfFetch();
    }
  }
  setPickupAddressEnable = (type,row) =>{
    // type  1:启用   2:禁用
    let params={}
    params.id=row.Id;
    if(type===1){
      params.enable=true;
    }else{
      params.enable=false;
    }
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/SetPickupAddressEnable`,
      payload: params,
      callBack: {
        success: (data) => {
          if(type===1){
            message.success("已开启");
          }else{
            message.success("已禁用");
          }
          this.getAddressList();
        },
        error: (data) => {
          if(type===1){
            message.success("开启失败：" + data.Msg);
          }else{
            message.success("禁用失败：" + data.Msg);
          }
        }
      }
    });
  }
  confirmPickupAddressEnable = (type,row) =>{
    this.setPickupAddressEnable(type,row);
  }
  deletePickupAddress = (id) =>{
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/DeletePickupAddress`,
      payload: {id:id},
      callBack: {
        success: (data) => {
          message.success("删除成功");
          this.getAddressList();
        },
        error: (data) => {
          message.error("删除失败：" + data.Msg);
        }
      }
    });
  }
  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 3 },
        sm: { span: 3 },
        md: { span: 3 },

      },
      wrapperCol: {
        xs: { span: 21 },
        sm: { span: 21 },
        md: { span: 21 },
      },
    };
    const {
      getFieldDecorator, getFieldsError, getFieldError, isFieldTouched, getFieldValue
    } = this.props.form;
    const { addressList,configLoading } = this.props;
    const { loadBtn, paginationProps, loading, selfFetchConfig, switchLoading, editData,pageLoading } = this.state;

    const columns = [{
      title: '自提点名称',
      dataIndex: 'Name',
      align:'left',
      key: 'Name',
    }, {
      title: '地址',
      render: (text, record )=>{
        return <span>{`${record.Prov}${record.City}${record.District}${record.Address}`}</span>
      }
    }, {
      title: '联系方式 ',
      align:'left',
      dataIndex: 'ContactTel',
      key: 'ContactTel',
    }, {
      title: '状态 ',
      align:'left',
      render: (text, record )=>{
        return <div className={styles.Enable}>
          {record.Enable?<span className={styles.isEnable}>已启用</span>:<span className={styles.noEnable}>已禁用</span>}
        </div>
      }
    }, {
      title: '操作 ',
      align:'right',
      render: (text, record )=>{
        return <div className={styles.setting}>
            {record.Enable?
            <Popconfirm title="确定禁用？" onConfirm={()=>this.confirmPickupAddressEnable(2,record)} okText="确定" cancelText="取消">
              <a href="javascript:void(0)">禁用</a>
            </Popconfirm>:
            <Popconfirm title="确定启用？" onConfirm={()=>this.confirmPickupAddressEnable(1,record)} okText="确定" cancelText="取消">
              <a href="javascript:void(0)">启用</a>
            </Popconfirm>
            }

          <a href="javascript:void(0)" onClick={()=>this.editRow(record)}>编辑</a>

          <Popconfirm title="确定删除？" onConfirm={()=>this.deletePickupAddress(record.Id)} okText="确定" cancelText="取消">
            <a href="javascript:void(0)">删除</a>
          </Popconfirm>
        </div>
      }
    }];
    return (
      <Fragment>
        <Spin spinning={pageLoading} >
        <Card
            title="上门自提功能"
            bordered={false}
            className={styles.ExpressTitle}
          >
            <div>
            启用上门自提功能后，买家可以就近选择你预设的自提点，下单后你需要尽快将商品配送至指定自提点。
            <a>查看【上门自提】功能使用教程</a>
            </div>
            <Switch
              onChange={this.setSelfFetchConfig}
              checked={selfFetchConfig && selfFetchConfig.Enable}
              loading={switchLoading}
            />
          </Card>
        <Card
          title="上门自提设置"
          bordered={false}
          className={styles.ExpressSet}
        >
          <Form >
            <FormItem
              {...formItemLayout}
              label="支付方式"
            >
              {getFieldDecorator('Payment', {
                rules: [{ required: true, message: '请选择至少一种支付方式' }],
              })(
                <Checkbox.Group >
                  <Checkbox value={1}>在线支付</Checkbox>
                  <Checkbox value={2}>货到付款</Checkbox>
                </Checkbox.Group>
              )}

            </FormItem>

            <Row>
              <Col offset={3}>
                <Button
                  type="primary"
                  // htmlType="submit"
                  loading={loadBtn}
                  onClick={this.handleSubmit}
                >
                  保存
              </Button>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card
          title="自提点设置"
          bordered={false}
          className={styles.selfFetch}
        >
          <div style={{marginBottom:16}}>
            <Button
                type="primary"
                // htmlType="submit"
                loading={loadBtn}
                onClick={this.addSelfFetch}
              >
                新增自提点
              </Button>
            </div>
            <Spin spinning={loading} >
              <Table
                bordered={false}
                loading={false}
                rowKey={record => record.Id}
                dataSource={addressList.PageData}
                //dataSource={dataSource}
                columns={columns}
                onChange={this.handleTableChange}
                pagination={{
                  ...paginationProps
                }}
              />
            </Spin>

        </Card>
        <AddSelfFetch getAddressList={this.getAddressList} dispatch={this.props.dispatch} onRef={(ref)=>this.SelfFetch=ref} />
        <EditSelfFetch editData={editData} getAddressList={this.getAddressList} dispatch={this.props.dispatch} onRef={(ref)=>this.editSelfFetch=ref}/>
        </Spin>
      </Fragment>
    )
  }
}
export default connect(({ selfFetch, global, loading }) => ({
  addressList: selfFetch.addressList,
  loading: loading.effects['selfFetch/GetPickupAddressPageData'],
  configLoading: loading.effects['selfFetch/GetSelfFetchConfig'],
}))(SelfFetch);
